package com.muyu.danmo.service.impl;

import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.danmo.domain.*;
import com.muyu.danmo.domain.vo.DanmoPersonInfoVo;
import com.muyu.danmo.mapper.*;
import com.muyu.danmo.req.DanmoAncientDynastiesReq;
import com.muyu.danmo.req.DanmoInformationContyReq;
import com.muyu.danmo.service.IDanmoInformationService;
import com.muyu.danmo.util.GetPinyinInitial;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.util.*;

/**
 * 个人信息Service业务层处理
 *
 * @author yangle
 * @date 2024-09-03
 */
@Log4j2
@Service
public class DanmoInformationServiceImpl implements IDanmoInformationService {

    @Autowired
    private DanmoInformationMapper danmoInformationMapper;

    @Autowired
    private DanmoInformationMapTitleMapper danmoInformationMapTitleMapper;

    @Autowired
    private DanmoInformationShoppingMapper danmoInformationShoppingMapper;

    /**
     * 查询个人信息
     *
     * @param id 个人信息主键
     * @return 个人信息
     */
    @Override
    public DanmoInformation selectDanmoInformationById(Long id) {
        DanmoInformation danmoInformation = danmoInformationMapper.selectDanmoInformationById(id);
        List<DanmoInformationShopping> danmoInformationShopping = danmoInformationShoppingMapper.selectDanmoInformationShoppingByIdList(id);
        Long[] ids = new Long[danmoInformationShopping.size()];
        for (int i = 0; i < danmoInformationShopping.size(); i++) {
            ids[i] = danmoInformationShopping.get(i).getShoppingId();
        }
        if (ids.length != 0){
            List<DanmoShoppingProducts> danmoShoppingProductsList = danmoInformationShoppingMapper.selectAllShoppingList(ids);
            danmoInformation.setDanmoShoppingProductsList(danmoShoppingProductsList);
        }
        List<DanmoInformationContent> danmoInformationContentList = danmoInformation.getDanmoInformationContentList();
        for (DanmoInformationContent danmoInformationContent : danmoInformationContentList) {
            String atlas = danmoInformationContent.getAtlas();

            // 如果 atlas 为 null 或空字符串，则跳过处理或赋予一个默认值
            if (atlas != null && !atlas.isEmpty()) {
                String[] photoPaths = atlas.split(",");
                List<DanmoAtlasList> atlasList = new ArrayList<>();

                for (String photoPath : photoPaths) {
                    atlasList.add(new DanmoAtlasList(photoPath)); // 创建 DanmoAtlasList 对象并添加到列表中
                }

                danmoInformationContent.setAtlasList(atlasList); // 设置 DanmoAtlasList 对象的列表
            } else {
                // 如果 atlas 为 null 或空字符串，可以选择处理逻辑，如清空或不做任何操作
                danmoInformationContent.setAtlasList(new ArrayList<>());
            }
        }

        return danmoInformation;
    }

    /**
     * 查询个人信息列表
     *
     * @param danmoInformation 个人信息
     * @return 个人信息
     */
    @Override
    public List<DanmoInformation> selectDanmoInformationList(DanmoInformation danmoInformation) {
        // 获取 DanmoInformation 列表
        List<DanmoInformation> danmoInformations = danmoInformationMapper.selectDanmoInformationList(danmoInformation);


        return danmoInformations;
    }

    // 按照姓名的姓氏拼音排序
//        danmoInformations.sort(Comparator.comparing(this::getLastNamePinyin));

//    private String getLastNamePinyin(DanmoInformation danmoInformation) {
//        String name = danmoInformation.getName();
//        if (name != null && !name.isEmpty()) {
//            char lastNameChar = name.charAt(0);  // 获取姓氏（假设名字的第一个字为姓）
//            return getPinyin(lastNameChar);  // 获取姓氏的拼音
//        }
//        return "";  // 如果没有名字，返回空字符串
//    }
//
//    private String getPinyin(char c) {
//        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
//        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
//        try {
//            // 获取拼音数组
//            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
//            if (pinyinArray != null && pinyinArray.length > 0) {
//                return pinyinArray[0];  // 获取拼音（完整拼音）
//            }
//        } catch (BadHanyuPinyinOutputFormatCombination e) {
//            e.printStackTrace();
//        }
//        return "";  // 如果无法转换成拼音，返回空字符串
//    }


    /**
     * 新增个人信息
     *
     * @param danmoInformation 个人信息
     * @return 结果
     */
    @Autowired
    private DanmoProvinceMapper danmoProvinceMapper;
    @Autowired
    private DanmoPortfolioMapper danmoPortfolioMapper;

    @Autowired
    private DanmoInformationBarMapper danmoInformationBarMapper;
    @Autowired
    private DanmoInformationContentMapper danmoInformationContentMapper;

    @Autowired
    private DanmoInformationCalligrapherPositionMapper danmoInformationCalligrapherPositionMapper;
    @Autowired
    private DanmoPersonalPicturesMapper danmoPersonalPicturesMapper;

    @Autowired
    private DanmoInformationMapMapper danmoInformationMapMapper;


    @Override
    public Result insertDanmoInformation(DanmoInformation danmoInformation) {
//        try {
////            Result verification = verification(danmoInformation);
////            if (verification!=null){
////                return verification;
////            }
//            danmoInformation.setName(danmoInformation.getDanmoInformationBar().getChineseName());
//            danmoInformation.setCreateTime(DateUtils.getNowDate());
        danmoInformationMapper.insertDanmoInformation(danmoInformation);
//            DanmoInformation danmoInformation1 = new DanmoInformation();
//            danmoInformation1.setUserId(danmoInformation.getUserId());
//            List<DanmoInformation> danmoInformations = danmoInformationMapper.selectDanmoInformationList(danmoInformation1);
//            if (danmoInformations.size()>0){
//                return Result.error("只可以添加一次");
//            }
//            danmoInformationMapper.insertDanmoInformation(danmoInformation);
//            Long id = danmoInformation.getId();
//            List<DanmoPersonalPictures> danmoPersonalPicturesList = danmoInformation.getDanmoPersonalPicturesList();
//            if (danmoPersonalPicturesList != null) {
//                for (DanmoPersonalPictures danmoPersonalPictures : danmoPersonalPicturesList) {
//                    danmoPersonalPictures.setInformationId(id);
//                    danmoPersonalPicturesMapper.insertDanmoPersonalPictures(danmoPersonalPictures);
//                }
//            }
//
///*            List<DanmoInformationMap> danmoInformationMapList = danmoInformation.getDanmoInformationMapList();
//            if (danmoInformationMapList != null || !danmoInformationMapList.get(0).getName().equals("")) {
//                for (DanmoInformationMap danmoInformationMap : danmoInformationMapList) {
//                    danmoInformationMap.setInformationId(id);
//                    danmoInformationMapMapper.insertDanmoInformationMap(danmoInformationMap);
//                }
//            }*/
//
//            List<DanmoInformationMapTitle> danmoInformationMapTitleList = danmoInformation.getDanmoInformationMapTitleList();
//            if (danmoInformationMapTitleList != null || !danmoInformationMapTitleList.get(0).getTitle().equals("")) {
//                for (DanmoInformationMapTitle danmoInformationMapTitle : danmoInformationMapTitleList) {
//                    danmoInformationMapTitle.setInformationId(id);
//                    danmoInformationMapTitle.setViews(0L);
//                    danmoInformationMapTitleMapper.insertDanmoInformationMapTitle(danmoInformationMapTitle);
//                    List<DanmoInformationMap> danmoInformationMapList = danmoInformationMapTitle.getDanmoInformationMapList();
//                    if (danmoInformationMapList != null || !danmoInformationMapList.get(0).getName().equals("")) {
//                        for (DanmoInformationMap danmoInformationMap : danmoInformationMapList) {
//                            danmoInformationMap.setInformationId(id);
//                            danmoInformationMap.setMapTitleId(danmoInformationMapTitle.getId());
//                            danmoInformationMapMapper.insertDanmoInformationMap(danmoInformationMap);
//                        }
//                    }
//                }
//            }
//
//            DanmoInformationBar danmoInformationBar = danmoInformation.getDanmoInformationBar();
//            if (danmoInformationBar != null) {
//                danmoInformationBar.setInformationId(id);
//                danmoInformationBarMapper.insertDanmoInformationBar(danmoInformationBar);
//                for (DanmoInformationPhotos danmoInformationPhotos : danmoInformation.getDanmoInformationPhotosList()) {
//                    danmoInformationPhotos.setInformationId(id);
//                    danmoInformationMapper.insertDanmoInformationPhotos(danmoInformationPhotos);
//                }
//            }
//
//            for (DanmoInformationContent danmoInformationContent : danmoInformation.getDanmoInformationContentList()) {
//                danmoInformationContent.setInformationId(id);
//                String jsonObject = URLDecoder.decode(danmoInformationContent.getRichText(), "utf-8");
//                danmoInformationContent.setRichText(jsonObject);
//                danmoInformationContentMapper.insertDanmoInformationContent(danmoInformationContent);
//            }
//            DanmoInformationCalligrapherPosition danmoInformationCalligrapherPosition = new DanmoInformationCalligrapherPosition();
//            danmoInformationCalligrapherPosition.setInformationId(id);
//            danmoInformationCalligrapherPosition.setPositionId(danmoInformation.getPositionId());
//            danmoInformationCalligrapherPositionMapper.insertDanmoInformationCalligrapherPosition(danmoInformationCalligrapherPosition);


            return Result.success(danmoInformation, "添加成功");
//        } catch (Exception e) {
//            return Result.error("添加失败");
//        }
    }

    /**
     * 修改个人信息
     *
     * @param danmoInformation 个人信息
     * @return 结果
     */
    @Override
    public Result updateDanmoInformation(DanmoInformation danmoInformation) {
        try {
//            Result verification = verification(danmoInformation);
//            if (verification != null) {
//                return verification;
//            }
            Long id = danmoInformation.getId();
            danmoInformation.setName(danmoInformation.getDanmoInformationBar().getChineseName());
            danmoInformation.setUpdateTime(DateUtils.getNowDate());
            danmoInformationMapper.updateDanmoInformation(danmoInformation);


//            先将所有旧数据全部删掉
            danmoPersonalPicturesMapper.deleteDanmoPersonalPicturesByInformationId(danmoInformation.getId());
            danmoInformationMapTitleMapper.deleteDanmoInformationMapTitleByInformationId(id);
            List<DanmoInformationMapTitle> danmoInformationMapTitleList1 = danmoInformation.getDanmoInformationMapTitleList();
            if (danmoInformationMapTitleList1 != null){
                for (DanmoInformationMapTitle danmoInformationMapTitle : danmoInformationMapTitleList1) {
                    Long mapTitleId = danmoInformationMapTitle.getId();
                    danmoInformationMapMapper.deleteDanmoInformationMapByMapTitleId(mapTitleId);
                }
            }
            danmoInformationBarMapper.deleteDanmoInformationBarByInformationId(id);
            danmoInformationMapper.deleteDanmoInformationPhotosByInformationId(id);
            danmoInformationCalligrapherPositionMapper.deleteDanmoInformationCalligrapherPositionByInformationId(id);
            danmoInformationContentMapper.deleteDanmoInformationContentByContentInformationId(id);

            List<DanmoPersonalPictures> danmoPersonalPicturesList = danmoInformation.getDanmoPersonalPicturesList();
            if (danmoPersonalPicturesList != null){
                for (DanmoPersonalPictures danmoPersonalPictures : danmoPersonalPicturesList) {
                    danmoPersonalPictures.setInformationId(id);
                    danmoPersonalPicturesMapper.insertDanmoPersonalPictures(danmoPersonalPictures);
                }
            }


            List<DanmoInformationMapTitle> danmoInformationMapTitleList = danmoInformation.getDanmoInformationMapTitleList();
            if (danmoInformationMapTitleList != null || !danmoInformationMapTitleList.get(0).getTitle().equals("")) {
                for (DanmoInformationMapTitle danmoInformationMapTitle : danmoInformationMapTitleList) {
                    danmoInformationMapTitle.setInformationId(id);
                    danmoInformationMapTitle.setViews(0L);
                    danmoInformationMapTitleMapper.insertDanmoInformationMapTitle(danmoInformationMapTitle);
                    List<DanmoInformationMap> danmoInformationMapList = danmoInformationMapTitle.getDanmoInformationMapList();
                    if (danmoInformationMapList != null || !danmoInformationMapList.get(0).getName().equals("")) {
                        for (DanmoInformationMap danmoInformationMap : danmoInformationMapList) {
                            danmoInformationMap.setInformationId(id);
                            danmoInformationMap.setMapTitleId(danmoInformationMapTitle.getId());
                            danmoInformationMapMapper.insertDanmoInformationMap(danmoInformationMap);
                        }
                    }
                }
            }

            DanmoInformationBar danmoInformationBar = danmoInformation.getDanmoInformationBar();
            if (danmoInformationBar != null) {
                danmoInformationBar.setInformationId(id);
                danmoInformationBarMapper.insertDanmoInformationBar(danmoInformationBar);
                for (DanmoInformationPhotos danmoInformationPhotos : danmoInformation.getDanmoInformationPhotosList()) {
                    danmoInformationPhotos.setInformationId(id);
                    danmoInformationMapper.insertDanmoInformationPhotos(danmoInformationPhotos);
                }
            }

            for (DanmoInformationContent danmoInformationContent : danmoInformation.getDanmoInformationContentList()) {
                danmoInformationContent.setInformationId(id);
                String jsonObject = URLDecoder.decode(danmoInformationContent.getRichText(), "utf-8");
                danmoInformationContent.setRichText(jsonObject);
                danmoInformationContentMapper.insertDanmoInformationContent(danmoInformationContent);
            }
            DanmoInformationCalligrapherPosition danmoInformationCalligrapherPosition = new DanmoInformationCalligrapherPosition();
            danmoInformationCalligrapherPosition.setInformationId(id);
            danmoInformationCalligrapherPosition.setPositionId(danmoInformation.getPositionId());
            danmoInformationCalligrapherPositionMapper.insertDanmoInformationCalligrapherPosition(danmoInformationCalligrapherPosition);

            return Result.success(danmoInformation, "修改成功");
        } catch (Exception e) {
            return Result.error("修改失败");
        }

    }

    private Result verification(DanmoInformation danmoInformation) {
        if (danmoInformation.getName() == null || danmoInformation.getName().equals("")) {
            return Result.error("请输入姓名");
        }
        if (danmoInformation.getProvince() == null || danmoInformation.getProvince().equals("")) {
            return Result.error("请选择省份");
        }
        if (danmoInformation.getCitycode() == null || danmoInformation.getCitycode().equals("")) {
            return Result.error("请选择市");
        }
        if (danmoInformation.getCountycode() == null || danmoInformation.getCountycode().equals("")) {
            return Result.error("请选择县");
        }
        return null;
    }

    /**
     * 批量删除个人信息
     *
     * @param ids 需要删除的个人信息主键
     * @return 结果
     */
    @Override
    public Result deleteDanmoInformationByIds(Long[] ids) {
        try {
            danmoInformationMapper.deleteDanmoInformationByIds(ids);
            return Result.success(ids, "删除成功");
        } catch (Exception e) {
            return Result.error("删除失败");
        }

    }

    /**
     * 删除个人信息信息
     *
     * @param id 个人信息主键
     * @return 结果
     */
    @Override
    public int deleteDanmoInformationById(Long id) {
        return danmoInformationMapper.deleteDanmoInformationById(id);
    }


    @Override
    public List<DanmoProvince> selectProvince(String cityCode, String countyCode) {
        List<DanmoProvince> danmoProvinceList = danmoProvinceMapper.selectProvince(cityCode, countyCode);
        log.error(danmoProvinceList);
        return findProvince(danmoProvinceList, cityCode, countyCode);
    }

    /**
     * 查询县编码查人
     *
     * @param danmoInformationContyReq
     * @return
     */
    @Override
    public List<DanmoInformation> selectCounty(DanmoInformationContyReq danmoInformationContyReq) {
        return danmoInformationMapper.selectCounty(danmoInformationContyReq);
    }

    @Override
    public List<DanmoInformation> selectDynasty(DanmoAncientDynastiesReq danmoAncientDynastiesReq) {
        return danmoInformationMapper.selectDynasty(danmoAncientDynastiesReq);
    }

    @Override
    public DanmoInformation selectInformationPortfolio(Long informationId) {
        return danmoInformationMapper.selectInformationPortfolio(informationId);
    }

    @Override
    public List<DanmoPersonInfoVo> selectrecommended(DanmoInformation danmoInformation) {
        List<DanmoPersonInfoVo> selectrecommended = danmoInformationMapper.selectrecommended(danmoInformation);

        return selectrecommended;
    }

    @Override
    public DanmoInformation selectDanmoInformationUserId(Long userId) {
        return danmoInformationMapper.selectDanmoInformationUserId(userId);
    }

    @Override
    public Map<String, Object> list(DanmoInformation danmoInformation) {
        // 获取所有 DanmoInformation 列表
        List<DanmoInformation> danmoInformations = danmoInformationMapper.selectDanmoInformationList(danmoInformation);
        Map<String, List<DanmoInformation>> map = new HashMap<>();
        Map<String, Map<String, List<DanmoInformation>>> maps = new HashMap<>();
//        遍历 DanmoInformation 并按照拼音首字母分组
        for (DanmoInformation danmoInformation1 : danmoInformations) {
            String name = danmoInformation1.getAddressCity();
            List<DanmoInformation> danmoInformationList = map.getOrDefault(name, new ArrayList<>());
            danmoInformationList.add(danmoInformation1);
            map.put(name, danmoInformationList);

            List<String> allInitials = new ArrayList<>(map.keySet()); // 获取所有省份
//            Map<String, List<String>> groupedProvinces = groupProvincesByInitial(allInitials);
            Map<String, Object> results = new HashMap<>();
//            for (String s : groupedProvinces.keySet()) {
//                Map<String, Object> result = new HashMap<>();
//                List<String> strings = groupedProvinces.get(s);
//                for (String string : strings) {
//                    result.put(string, map.get(string));
//                }
//                results.put(s, result);
//            }
            return null;
/*            // 添加空值检查
            if (name != null && !name.isEmpty()) {
                String initial = GetPinyinInitial.getPinyinInitial(name); // 获取拼音首字母并转为大写

                if (!initial.isEmpty()) {  // 确保拼音首字母不为空
//                    List<DanmoInformation> danmoInformationList = map.getOrDefault(initial, new ArrayList<>());
//                    danmoInformationList.add(danmoInformation1);
                    mapByProvinces.put(initial, map);
                }
            }*/
        }
//
//        for (String s : map.keySet()) {
//            List<DanmoInformation> danmoInformationList = map.get(s);
//            for (DanmoInformation information : danmoInformationList) {
//                String name = information.getAddressCity();
//                List<DanmoInformation> danmoInformationLists = map.getOrDefault(name, new ArrayList<>());
//                danmoInformationList.add(information);
//                maps.put(s, danmoInformationList);
//            }
//        }



/*        for (String s : map.keySet()) {
            if (s.isEmpty() || s.equals("")) {
                continue;
            }
            String initial = getPinyinInitial(s);
            if (!initial.isEmpty()) {
                if ()
                Map<String, Object> maps = new HashMap<>();
                String name = "";

                List<DanmoInformation> danmoInformationList1 = new ArrayList<>();
        Map<String, Object> result = new HashMap<>();
                List<DanmoInformation> danmoInformationList = map.get(s);
                name = danmoInformationList.get(0).getAddressEntry();
                List<DanmoInformation> tempList = new ArrayList<>(danmoInformationList); // 创建临时列表
               *//* for (DanmoInformation information : tempList) {
                    name = information.getAddressEntry();
                    danmoInformationList1 = map.getOrDefault(name, new ArrayList<>());
                    if (danmoInformationList1 != null){
                        danmoInformationList1.add(information);
                        break;
                    }else {
                        danmoInformationList1.add(information); // 将信息添加到新的列表中
                    }
                }*//*
                maps.put(name, danmoInformationList);
*//*                if (!name.equals("") && danmoInformationList1 != null){
                    maps.put(name, danmoInformationList);
                }*//*
                mapByProvinces.put(initial, maps);
            }
        }*/

//        return mapByProvinces;


/*        // 确保返回的 Map 中每个键对应的列表都不为空
        map.values().removeIf(List::isEmpty);

        // 获取所有省的首字母
        List<String> allInitials = getAllProvinceInitials();

        // 初始化返回数据
        List<String> indexList = new ArrayList<>();
        Map<String, Object> result = new HashMap<>();
        Map<String, List<DanmoInformation>> itemArr = new LinkedHashMap<>();*/

        // 按照拼音首字母排序，并构建 indexList 和 itemArr
//        for (String initial : allInitials) {
//            indexList.add(initial);  // 拼音首字母作为 indexList
//            List<DanmoInformation> list = map.getOrDefault(initial, new ArrayList<>());
//            itemArr.put(initial, list);  // 对应拼音首字母的 DanmoInformation 列表
//            result.put("letter", map.get(initial).get(0).getAddressEntry());
//        }

        // 返回最终结果

//        result.put("indexList", indexList);  // 拼音首字母列表
//        result.put("letter", itemArr);      // 对应的列表，拼音首字母为键
//        Map<Object, Object> resultMap = new HashMap<>();
//        resultMap.put(result, itemArr);
     return null;
    }


    /**
     * 获取所有首字母相同的省份
     *
     * @param
     * @return
     */
//    public static Map<String, List<String>> groupProvincesByInitial(List<String> provinces) {
//        Map<String, List<String>> initialProvinceMap = new HashMap<>();
//
//        for (String province : provinces) {
//            if (!province.equals("")) {
//                String initial = getPinyinInitial(province);// 获取拼音首字母
//
//                // 将省份加入到对应的首字母列表中
//                initialProvinceMap.computeIfAbsent(initial, k -> new ArrayList<>()).add(province);
//            }
//        }
//
//        return initialProvinceMap;
//    }

    @Override
    public List<DanmoInformation> selectAncient(DanmoInformation danmoInformation) {
        return danmoInformationMapper.selectAncient(danmoInformation);
    }

    @Override
    public List<DanmoInformation> selectMass(DanmoInformation danmoInformation) {
        return danmoInformationMapper.selectMass(danmoInformation);
    }

    @Override
    public List<DanmoInformation> selectArtLover(DanmoInformation danmoInformation) {
        return danmoInformationMapper.selectArtLover(danmoInformation);
    }

    @Override
    public List<DanmoInformation> getInfo(DanmoInformation danmoInformation) {
        String tableName = determineTable(danmoInformation.getAssociationType());
        List<DanmoInformation> danmoInformationList = danmoInformationMapper.getInfo(danmoInformation, tableName);

        return  danmoInformationList;

    }
/**
 * 没有按照姓氏进行排序
 */
    @Override
    public List<Map<String, List<Map<String, List<DanmoInformation>>>>> select(DanmoInformation danmoInformation) {
//        // 获取所有数据
//        List<Map<String, List<DanmoInformation>>> danmoInformations = selectDanmoInformationList(danmoInformation);
//        // 按拼音首字母分组
//        Map<String, List<Map<String, List<DanmoInformation>>>> groupedData = new LinkedHashMap<>();
//
//        for (DanmoInformation information : danmoInformations) {
//            // 获取地址项
//            String addressEntry = information.getAddressEntry();
//
//            // 获取拼音首字母
//            String firstLetter = GetPinyinInitial.getPinyinInitial(addressEntry);
//            if (firstLetter.isEmpty()) {
//                continue;
//            }
//
//            // 如果拼音首字母没有被分组，初始化一个新的 List
//            List<Map<String, List<DanmoInformation>>> letterGroup = groupedData.computeIfAbsent(firstLetter, k -> new ArrayList<>());
//
//            // 根据地址项检查是否已经存在该地址，如果没有则初始化
//            Optional<Map<String, List<DanmoInformation>>> existingAddressGroup = letterGroup.stream()
//                    .filter(group -> group.containsKey(addressEntry))
//                    .findFirst();
//
//            if (existingAddressGroup.isPresent()) {
//                // 如果该地址已经存在，直接加入新的 DanmoInformation 数据
//                Map<String, List<DanmoInformation>> addressGroup = existingAddressGroup.get();
//                addressGroup.get(addressEntry).add(information);
//            } else {
//                // 否则新建一个 Map 存储该地址和数据
//                Map<String, List<DanmoInformation>> addressGroup = new LinkedHashMap<>();
//                addressGroup.put(addressEntry, new ArrayList<>(List.of(information)));
//                letterGroup.add(addressGroup);
//            }
//        }
//
//        // 将 Map 转换为 List 格式
//        List<Map<String, List<Map<String, List<DanmoInformation>>>>> result = new ArrayList<>();
//        for (Map.Entry<String, List<Map<String, List<DanmoInformation>>>> entry : groupedData.entrySet()) {
//            Map<String, List<Map<String, List<DanmoInformation>>>> group = new LinkedHashMap<>();
//            group.put(entry.getKey(), entry.getValue());
//            result.add(group);
//        }
//
//
//        return result;

        // 获取所有数据，假设 selectDanmoInformationList 返回的是按某种方式分组的数据
        List<Map<String, List<DanmoInformation>>> danmoInformations = selectList(danmoInformation);

        // 按拼音首字母分组
        Map<String, List<Map<String, List<DanmoInformation>>>> groupedData = new LinkedHashMap<>();

        for (Map<String, List<DanmoInformation>> group : danmoInformations) {
            for (Map.Entry<String, List<DanmoInformation>> entry : group.entrySet()) {
                // 获取每组的地址项（可以从数据中取得）
                List<DanmoInformation> informationList = entry.getValue();
                for (DanmoInformation information : informationList) {
                    String addressEntry = information.getAddressEntry();

                    // 获取拼音首字母
                    String firstLetter = GetPinyinInitial.getPinyinInitial(addressEntry);
                    if (firstLetter.isEmpty()) {
                        continue;  // 跳过没有拼音首字母的数据
                    }

                    // 如果拼音首字母没有被分组，初始化一个新的 List
                    List<Map<String, List<DanmoInformation>>> letterGroup = groupedData.computeIfAbsent(firstLetter, k -> new ArrayList<>());

                    // 检查是否已经存在该地址项
                    Optional<Map<String, List<DanmoInformation>>> existingAddressGroup = letterGroup.stream()
                            .filter(groupMap -> groupMap.containsKey(addressEntry))
                            .findFirst();

                    if (existingAddressGroup.isPresent()) {
                        // 如果该地址已经存在，直接加入新的 DanmoInformation 数据
                        Map<String, List<DanmoInformation>> addressGroup = existingAddressGroup.get();
                        addressGroup.get(addressEntry).add(information);
                    } else {
                        // 否则新建一个 Map 存储该地址和数据
                        Map<String, List<DanmoInformation>> addressGroup = new LinkedHashMap<>();
                        addressGroup.put(addressEntry, new ArrayList<>(List.of(information)));
                        letterGroup.add(addressGroup);
                    }
                }
            }
        }

        // 按照字母顺序排序 Map（按照拼音首字母）
        Map<String, List<Map<String, List<DanmoInformation>>>> sortedGroupedData = new TreeMap<>(groupedData);

        // 将排序后的 Map 转换为 List 格式
        List<Map<String, List<Map<String, List<DanmoInformation>>>>> result = new ArrayList<>();
        for (Map.Entry<String, List<Map<String, List<DanmoInformation>>>> entry : sortedGroupedData.entrySet()) {
            Map<String, List<Map<String, List<DanmoInformation>>>> group = new LinkedHashMap<>();
            group.put(entry.getKey(), entry.getValue());
            result.add(group);
        }

        return result;
    }

    @Override
    public List<Map<String, List<DanmoInformation>>> selectList(DanmoInformation danmoInformation) {
        // 获取 DanmoInformation 列表
        List<DanmoInformation> danmoInformations = danmoInformationMapper.selectDanmoInformationList(danmoInformation);

        // 创建一个Map，用来保存拼音首字母分组后的结果
        Map<String, List<DanmoInformation>> groupedData = new TreeMap<>();

        // 按照拼音首字母分组
        for (DanmoInformation information : danmoInformations) {
            // 获取拼音首字母（不会修改原来的 name 字段）
            String pinyinInitial = GetPinyinInitial.getPinyinInitial(information.getName());

            // 如果拼音首字母为空，可以归类为 "others"
            if (pinyinInitial == null || pinyinInitial.isEmpty()) {
                pinyinInitial = "others";
            }

            // 将数据根据拼音首字母分类到 groupedData 中
            groupedData
                    .computeIfAbsent(pinyinInitial, k -> new ArrayList<>())
                    .add(information);
        }

        // 将分组结果转换为List形式，方便返回
        List<Map<String, List<DanmoInformation>>> result = new ArrayList<>();
        for (Map.Entry<String, List<DanmoInformation>> entry : groupedData.entrySet()) {
            Map<String, List<DanmoInformation>> group = new HashMap<>();
            group.put(entry.getKey(), entry.getValue());
            result.add(group);
        }

        // 返回结果
        return result;
    }


    @Override
    public List<Map<String, Map<String, List<Map<String, DanmoInformation>>>>> selectCouncil(DanmoInformation danmoInformation) {
        // 查询所有的 DanmoInformation
        List<DanmoInformation> danmoInformations = danmoInformationMapper.selectCouncil(danmoInformation);

        // 存放数据的 List
        List<Map<String, Map<String, List<Map<String, DanmoInformation>>>>> dataList = new ArrayList<>();

        // 使用 Map 按职位类别和职位名称分类
        Map<String, Map<String, List<Map<String, DanmoInformation>>>> positionMap = new HashMap<>();

        // 遍历所有 DanmoInformation 对象
        for (DanmoInformation information : danmoInformations) {
            String grade = information.getGrade();  // 例如：职位、理事
            String positionName = information.getPositionName();  // 例如：常务理事、普通理事等

            // 只有 grade 和 positionName 都不为 null 时，才执行逻辑
            if (grade != null && positionName != null) {

                DanmoInformation personalInfo = information;  // 个人信息

                // 确保类别（职位、理事）存在
                if (!positionMap.containsKey(grade)) {
                    positionMap.put(grade, new HashMap<>());
                }

                // 获取该类别下职位名称对应的 Map
                Map<String, List<Map<String, DanmoInformation>>> gradeMap = positionMap.get(grade);

                // 确保职位名称存在
                if (!gradeMap.containsKey(positionName)) {
                    gradeMap.put(positionName, new ArrayList<>());
                }

                // 仅当 personalInfo 不为 null 时，才将其放入 Map
                if (personalInfo != null) {
                    Map<String, DanmoInformation> personalInfoMap = new HashMap<>();
                    personalInfoMap.put("personalInfo", personalInfo);  // 只放入 non-null 值

                    // 将个人信息添加到对应职位名称下
                    gradeMap.get(positionName).add(personalInfoMap);
                }
            }
        }

        // 将职位 Map 转换为目标格式的 dataList
        for (Map.Entry<String, Map<String, List<Map<String, DanmoInformation>>>> entry : positionMap.entrySet()) {
            Map<String, Map<String, List<Map<String, DanmoInformation>>>> entryMap = new HashMap<>();
            entryMap.put(entry.getKey(), entry.getValue());
            dataList.add(entryMap);
        }

        return dataList;
    }



    @Override
    public List<Map<String, List<Map<String, List<Map<String, List<DanmoInformation>>>>>>> selectCities(DanmoInformation danmoInformation) {
        // 获取 DanmoInformation 列表
        List<DanmoInformation> danmoInformations = danmoInformationMapper.selectDanmoInformationList(danmoInformation);

        // 创建一个Map，用来保存拼音首字母分组后的结果
        Map<String, List<Map<String, List<Map<String, List<DanmoInformation>>>>>> groupedData = new TreeMap<>();

        // 按照拼音首字母分组
        for (DanmoInformation information : danmoInformations) {
            // 获取拼音首字母（不会修改原来的 name 字段）
            String pinyinInitial = GetPinyinInitial.getPinyinInitial(information.getAddressEntry());

            // 如果拼音首字母为空，可以归类为 "others"
            if (pinyinInitial == null || pinyinInitial.isEmpty()) {
                pinyinInitial = "others";
            }

            // 将数据根据拼音首字母分类到 groupedData 中
            groupedData.computeIfAbsent(pinyinInitial, k -> new ArrayList<>());

            // 获取省市名称和个人信息
            String regionName = information.getAddressEntry(); // 省市名称
            String cityName = information.getAddressCity(); // 城市名称
            DanmoInformation personalInfo = information; // 个人信息

            // 处理 null 值
            if (regionName == null || regionName.isEmpty()) {
                regionName = "未知";
            }
            if (cityName == null || cityName.isEmpty()) {
                cityName = "未知";
            }

            // 获取拼音首字母对应的区域列表
            List<Map<String, List<Map<String, List<DanmoInformation>>>>> regionList = groupedData.get(pinyinInitial);

            boolean regionFound = false;

            // 遍历区域列表并处理省市
            for (Map<String, List<Map<String, List<DanmoInformation>>>> regionMap : regionList) {
                if (regionMap.containsKey(regionName)) {
                    // 如果省市已经存在，继续查找城市
                    List<Map<String, List<DanmoInformation>>> cityList = regionMap.get(regionName);
                    boolean cityFound = false;

                    // 查找城市
                    for (Map<String, List<DanmoInformation>> cityMap : cityList) {
                        if (cityMap.containsKey(cityName)) {
                            // 找到城市，添加个人信息
                            cityMap.get(cityName).add(personalInfo);
                            cityFound = true;
                            break;
                        }
                    }

                    // 如果没有找到城市，则新建城市项
                    if (!cityFound) {
                        Map<String, List<DanmoInformation>> newCityMap = new HashMap<>();
                        newCityMap.put(cityName, new ArrayList<>(List.of(personalInfo)));
                        cityList.add(newCityMap);
                    }

                    regionFound = true;
                    break;
                }
            }

            // 如果没有找到对应的省市分组，创建新省市分组
            if (!regionFound) {
                Map<String, List<Map<String, List<DanmoInformation>>>> newRegionMap = new HashMap<>();
                List<Map<String, List<DanmoInformation>>> cityList = new ArrayList<>();
                Map<String, List<DanmoInformation>> newCityMap = new HashMap<>();
                newCityMap.put(cityName, new ArrayList<>(List.of(personalInfo)));
                cityList.add(newCityMap);
                newRegionMap.put(regionName, cityList);
                regionList.add(newRegionMap);
            }
        }

        // 将分组结果转换为List形式，方便返回
        List<Map<String, List<Map<String, List<Map<String, List<DanmoInformation>>>>>>> result = new ArrayList<>();
        for (Map.Entry<String, List<Map<String, List<Map<String, List<DanmoInformation>>>>>> entry : groupedData.entrySet()) {
            Map<String, List<Map<String, List<Map<String, List<DanmoInformation>>>>>> group = new HashMap<>();
            group.put(entry.getKey(), entry.getValue());
            result.add(group);
        }

        return result;
    }

    @Override
    public List<String> selectListyears(DanmoInformation danmoInformation) {
        // 使用 Set 来去重年份
        Set<String> yearSet = new HashSet<>();

        // 遍历查询结果，将年份添加到 Set 中，Set 会自动去重
        for (DanmoInformation information : danmoInformationMapper.selectAncient(danmoInformation)) {
            String year = information.getYear();
            if (year != null) {
                yearSet.add(year);
            }
        }
      // 排序 List（升序）
        List<String> sortedYears = new ArrayList<>(yearSet);
        Collections.sort(sortedYears);
        return sortedYears;

    }

    @Override
    public List<Long> selectSuccessive(DanmoInformation danmoInformation) {
        // 使用 Set 来去重年份
        Set<Long> severals = new HashSet<>();

        // 遍历查询结果，将年份添加到 Set 中，Set 会自动去重
        for (DanmoInformation information : danmoInformationMapper.selectAncient(danmoInformation)) {
            Long several = information.getSeveral();
            if (several != null) {
                severals.add(several);
            }
        }
        // 排序 List（升序）
        List<Long> sortedSeveral = new ArrayList<>(severals);
        Collections.sort(sortedSeveral);
        return sortedSeveral;
    }

    @Override
    public List<DanmoPersonInfoVo> calligraphy(DanmoInformation danmoInformation) {
        return danmoInformationMapper.calligraphy(danmoInformation);
    }


//    /**
//     * 按照姓氏进行排序
//     * @param danmoInformation
//     * @return
//     */
//
//@Override
//    public List<Map<String, List<Map<String, List<DanmoInformation>>>>> select(DanmoInformation danmoInformation) {
//        // 获取所有数据
//        List<DanmoInformation> danmoInformations = danmoInformationMapper.selectDanmoInformationList(danmoInformation);
//
//        // 按百家姓排序
//    BaiJiaXing service = new BaiJiaXing();
//        danmoInformations = service.sortDanmoInformationByBaijiaxing(danmoInformations);
//
//        // 按拼音首字母分组
//        Map<String, List<Map<String, List<DanmoInformation>>>> groupedData = new LinkedHashMap<>();
//
//        for (DanmoInformation information : danmoInformations) {
//            // 获取地址项
//            String addressEntry = information.getAddressEntry();
//
//            // 获取拼音首字母
//            String firstLetter = GetPinyinInitial.getPinyinInitial(addressEntry);
//            if (firstLetter.isEmpty()) {
//                continue;
//            }
//
//            // 如果拼音首字母没有被分组，初始化一个新的 List
//            List<Map<String, List<DanmoInformation>>> letterGroup = groupedData.computeIfAbsent(firstLetter, k -> new ArrayList<>());
//
//            // 根据地址项检查是否已经存在该地址，如果没有则初始化
//            Optional<Map<String, List<DanmoInformation>>> existingAddressGroup = letterGroup.stream()
//                    .filter(group -> group.containsKey(addressEntry))
//                    .findFirst();
//
//            if (existingAddressGroup.isPresent()) {
//                // 如果该地址已经存在，直接加入新的 DanmoInformation 数据
//                Map<String, List<DanmoInformation>> addressGroup = existingAddressGroup.get();
//                addressGroup.get(addressEntry).add(information);
//            } else {
//                // 否则新建一个 Map 存储该地址和数据
//                Map<String, List<DanmoInformation>> addressGroup = new LinkedHashMap<>();
//                addressGroup.put(addressEntry, new ArrayList<>(List.of(information)));
//                letterGroup.add(addressGroup);
//            }
//        }
//
//        // 将 Map 转换为 List 格式
//        List<Map<String, List<Map<String, List<DanmoInformation>>>>> result = new ArrayList<>();
//        for (Map.Entry<String, List<Map<String, List<DanmoInformation>>>> entry : groupedData.entrySet()) {
//            Map<String, List<Map<String, List<DanmoInformation>>>> group = new LinkedHashMap<>();
//            group.put(entry.getKey(), entry.getValue());
//            result.add(group);
//        }
//
//        return result;
//    }

    private String determineTable(Long associationType) {
      if (associationType == 1){
          return "danmo_information_countries";
      }

        return  "danmo_font_generate";
    }

    /**
     * 获取所有省的首字母
     *
     * @return 省的首字母列表
     */
//    private List<String> getAllProvinceInitials() {
//        List<DanmoProvince> provinces = danmoProvinceMapper.selectAllProvinces();
//        Set<String> initialsSet = new TreeSet<>(); // 使用 TreeSet 以确保首字母按字母排序
//
//        for (DanmoProvince province : provinces) {
//            String initial = getPinyinInitial(province.getName());
//            if (!initial.isEmpty()) {
//                initialsSet.add(initial);
//            }
//        }
//
//        return new ArrayList<>(initialsSet);
//    }


    private List<DanmoProvince> findProvince(List<DanmoProvince> list, String cityCode, String countyCode) {
        List<DanmoProvince> danmoProvinces = new ArrayList<>();
        for (DanmoProvince danmoProvince : list) {
            if (danmoProvince.getProvinceCode().equals(cityCode)) {
                if (danmoProvince.getCountyCode().equals(countyCode)) {
                    List<DanmoProvince> province = findProvince(list, danmoProvince.getCityCode(), danmoProvince.getCountyCode());
                    danmoProvince.setDanmoProvinceList(province);
                    danmoProvinces.add(danmoProvince);
                }
            }

        }
        return danmoProvinces;
    }

    public DanmoInformation selectUserID(Long userid) {
        return danmoInformationMapper.selectUserID(userid);
    }
}
